// pages/individual/active_detail/components/student/index.ts
import msg from "../../../../../utils/model/msg";
import {GetActiveDetail, GetTeacherLocation, UploadLocation } from '../../../../../utils/data/apis';
import { event } from "../../../../../utils/interface";
import {Marker} from "../../index";

let teacherOrderId: string = '';
let refleshTimer: undefined | number = void 0; // 刷新数据定时器
let dropCach = true; // 是否允许删除定位缓存
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    user: {
      type: Object
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    activeDetail: undefined, // 正在活动详情
    stuLocation: [23.5, 110], // 用户位置信息
    teaLocation: [{}], // 导师位置信息
    detailType: '学生信息', // 筛选内容
    teacherInfo: {}, // 导师信息
    showLocation: false, // 展示位置信息框？
    locationEaseOut: false, // 位置信息淡出动画
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
   * @function 获取正在活动数据
   */
  getData: async function() {
    const user: any = this.data.user;
    // 已登录
    msg.Loading();
    // 学生端
    return await GetActiveDetail({ 
      id: user.id, 
    }) // 获取正在活动数据
    .then((res: any) => {
      console.log(res.data);
      let activeDetail: any = void 0; // undefined
      let teacherInfo: any = void 0; // undefined
      if(res.data.data[0] !== '无正在进行的课程' && res.data.data.length > 0) {
        // 有数据
        activeDetail = res.data.data[0];
        if(activeDetail !== '该活动暂未分配老师') {
          activeDetail.starttime = activeDetail.starttime.replace(/-/g, '/');
          activeDetail.endtime = activeDetail.endtime.replace(/-/g, '/');
          teacherInfo = res.data.teacher[0]; // 导师信息
          teacherOrderId = res.data.data[0].teacherOrderId; // 存放ID
          this.getTeacherLocation(teacherOrderId); // 获取导师位置信息
          this.getLocation(activeDetail.courseid); // 获取用户位置信息
        }
        this.setData({
          activeDetail: activeDetail,
          teacherInfo: teacherInfo,
        })
        console.log('正在活动', activeDetail);
        console.log('导师信息', teacherInfo);
        msg.HideLoading();
        return;
      }
      // 无数据
      this.setData({
        activeDetail: void 0,
        teacherInfo: void 0,
      })
      msg.HideLoading();
    })
    .catch(() => {
      msg.HideLoading();
      msg.Fail('获取数据失败');
      setTimeout(() => {
        wx.navigateBack();
      }, 800)
    })
  },
  /**
   * @function 信息筛选框改变
   */
  filterChange: function(e: event) {
    const type = e.detail.type;
    this.setData({
      detailType: type,
    })
  },
  /**
   * @function 获取用户地理位置信息
   */
  getLocation: function(courseid: string) {
    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      isHighAccuracy: true,
      highAccuracyExpireTime: 3500
    })
    .then((res: WechatMiniprogram.GetLocationSuccessCallbackResult) => {
      console.log(res);
      wx.setStorageSync('location', JSON.stringify({
        latitude: res.latitude,
        longitude: res.longitude
      })) // 存储到缓存
      this.setData({
        stuLocation: [res.latitude, res.longitude],
      })
      // 上传位置信息
      this.uploadLocation(courseid, {
        latitude: res.latitude,
        longitude: res.longitude
      })
    })
    .catch(() => {
      const location: {longitude: number, latitude: number} = JSON.parse(wx.getStorageSync('location'));
      if('latitude' in location && 'longitude' in location) {
        // 有缓存记录，获取上次成功获取的数据
        console.log('获取到缓存中的位置信息')
        this.setData({
          stuLocation: [location.latitude, location.longitude],
        })
        return;
      }
      // 无缓存记录
      msg.Modal('请检查手机位置信息服务是否已打开', '定位失败');

    })
  },
  /**
   * @function 上传位置信息
   * @param courseid 课程id
   * @param location 位置信息
   */
  uploadLocation: function(courseid: string, location: {latitude: number, longitude: number}) {
    const user: any = wx.getStorageSync('user');
    // 上传学生位置信息
    UploadLocation({
      userid: user.id,
      courseid: courseid,
      longitude: location.longitude,
      latitude: location.latitude,
    })
    .then((result: any) => {
      if(result.data.data.msg == '上传位置成功') {
        // 上传成功
        return;
      }
    }) // 上传学生位置信息回调
    .catch(() => {

    }) // 上传学生位置信息失败
  },
  /**
   * @function 获取导师位置信息
   */
  getTeacherLocation: function(teaOrderId: string = teacherOrderId) {
    GetTeacherLocation({
      teaOrderId: teaOrderId
    })
    .then((res: any) => {
      console.log('导师位置', res.data.data);
      if(res.data.data.length > 0) {
        // 有数据，更新导师位置信息
        const marker: Array<Marker>= [];
        for(let i in res.data.data) {
          marker.push({
            id: parseInt(res.data.data[i].id),
            latitude: res.data.data[i].latitude, 
            longitude: res.data.data[i].longitude,
            iconPath: '/svg/location.png',
            width: '100rpx',
            height: '100rpx',
            title: '导师位置',
            zIndex: 999,
          })
        } 
        
        this.setData({
          teaLocation: marker
        })
      }
    })
  },
  /**
   * @function 显示位置信息框
   */
  showLocation: function() {
    let status: boolean = !this.data.showLocation;
    if(!status) {
      // 折叠
      this.setData({
        locationEaseOut: true, // 淡出动画
      })
    }
    else {
      this.setData({
        showLocation: status,
      })
      return;
    }
    const that = this;
    setTimeout(() => {
      that.setData({
        showLocation: status,
        locationEaseOut: false,
      })
    }, 250)
  },
  /**
   * @function 刷新数据
   */
  refleshData: function() {
    if(refleshTimer) {
      clearInterval(refleshTimer);
    }
    const that = this;
    refleshTimer = setInterval(() => {
      // 请求数据
      that.getTeacherLocation(teacherOrderId);
    }, 30000)
  },
  },
  lifetimes: {
    created: function() {
      const type = this.data.detailType;
      const showLocation = this.data.showLocation;
      this.setData({
        detailType: type,
        showLocation: showLocation,
      })
      dropCach = false; // 禁止位置信息缓存被释放
    },
    attached: function() {
      this.getData();
      this.refleshData();
    },
    detached: function() {
      dropCach = true;
      if(refleshTimer) {
        clearInterval(refleshTimer);
        refleshTimer = undefined;
      }
      setTimeout(() => {
        if(wx.getStorageSync('location').length > 0 && dropCach) {
          // 销毁缓存记录
          wx.removeStorageSync('location');
          console.log('已删除缓存位置信息');
        }
      }, 10000)
    }
  }
})
